<template>
  <div class="OperateRecord">
    <div v-show="customerId" style="height: 100%">
      <el-form :model="searchForm" style="display: flex">
        <el-form-item
          label="类型"
          prop="operateType"
          style="margin-right: 24px"
        >
          <el-select
            v-model="searchForm.operateType"
            filterable
            placeholder="请选择"
            size="mini"
            clearable
            @change="quickQuery"
          >
            <el-option
              v-for="item in getOperateType"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人" prop="operateUser">
          <el-select
            v-model="searchForm.operateUser"
            filterable
            placeholder="请选择"
            clearable
            size="mini"
            @change="quickQuery"
          >
            <el-option
              v-for="item in getOperate"
              :key="item._id"
              :label="item.agentName"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="line"></div>
      <Record
        v-if="recordData && recordData.length"
        ref="Record"
        style="height: 100%"
        :data="recordData"
        :allShow="allShow"
        @loadMore="loadMore"
      ></Record>
      <div v-else class="else">暂无操作日志</div>
    </div>
    <div v-show="!customerId" class="no-data"></div>
  </div>
</template>

<script lang="ts">
/**
 * 客户详情操作日志
 */
import { Component, Vue, Prop } from 'vue-property-decorator'
import Title from '../common/title.vue'
import Record from '../common/record.vue'
import { commonAction, checkHideTel } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
@Component({
  name: 'OperateRecord',
  components: {
    Title,
    Record
  }
})
export default class OperateRecord extends Vue {
  [x: string]: any
  @Prop() private customerId

  private recordData: any = []

  private searchForm: any = {}

  private pageData = {
    page: 1,
    limit: 10,
    total: 0
  }

  private allShow: boolean = false

  get cusAllFields () {
    return (CommonModule as any).publicCache.customerAllFields || []
  }

  get getOperate () {
    return CommonModule.publicCache.userList
  }

  get getOperateType () {
    return [
      {
        _id: 'create_customer_single_no_assign',
        name: '单条录入-不分配'
      },
      {
        _id: 'create_customer_single_assign',
        name: '单条录入-分配到人员'
      },
      {
        _id: 'incoming_auto_create',
        name: '来电自动保存'
      },
      {
        _id: 'manual_assign',
        name: '手动分配'
      },
      {
        _id: 'update_customer',
        name: '更改客户信息'
      },
      {
        _id: 'create_contactor',
        name: '新增联系人'
      },
      {
        _id: 'update_contactor',
        name: '更改联系人信息'
      },
      {
        _id: 'delete_contactor',
        name: '删除联系人'
      },
      {
        _id: 'create_contactor_address',
        name: '新增联系人地址'
      },
      {
        _id: 'update_contactor_address',
        name: '更改联系人地址'
      },
      {
        _id: 'delete_contactor_address',
        name: '删除联系人地址'
      },
      {
        _id: 'visitor_assign_customer',
        name: '关联客户'
      },
      {
        _id: 'cancel_assign_visitor_customer',
        name: '取消关联'
      },
      {
        _id: 'import_customer_no_assign',
        name: '导入客户-不分配'
      },
      {
        _id: 'import_customer_assign',
        name: '导入客户-分配到人员'
      },
      {
        _id: 'open_api_create_customer_no_assign',
        name: '接口创建-不分配'
      },
      {
        _id: 'open_api_create_customer_assign',
        name: '接口创建-分配到人员'
      },
      {
        _id: 'open_api_update_customer',
        name: '接口创建-更新客户'
      }
    ]
  }

  public clearSearchForm () {
    this.searchForm = {
      operateType: '',
      operateUser: ''
    }
  }

  private loadMore () {
    const { total, page, limit } = this.pageData
    if (total > page * limit) {
      this.pageData.page++
      this.getRecord()
    }
  }

  private getOperateTypeName (id: any) {
    const types = {}
    this.getOperateType.map(item => {
      types[item._id] = item.name
    })
    return types[id]
  }

  private getAgentName (id: any) {
    if (id === 'customer') {
      return '客户'
    }
    const agent = (CommonModule as any).publicCache.userListObj[id]
    if (agent) {
      return agent.agentName
    }
    return ''
  }

  private getLabel (key: any) {
    const labels = {
      name: '联系人姓名',
      phone: '手机号码',
      email: '邮箱',
      province: '省市区',
      detailAddress: '详细地址',
      owner: '分配给',
      address: '省市区',
      importBatchNumber: '导入批次'
    }

    if (labels[key]) {
      return labels[key]
    }

    return ''
  }

  private getArea (list: any = [], idx: number, allList: any = [], areaName: any = []) {
    allList.map((item: any) => {
      if (item.id === list[idx]) {
        areaName.push(item.fullname)
        if (item.children) {
          const num = idx + 1
          this.getArea(list, num, item.children, areaName)
        }
      }
    })
  }

  private getLabelObj (id: any) {
    const labels = (CommonModule as any).publicCache.customerAllLabelsObj[id]
    if (labels) {
      return labels.name
    }
  }

  private getSexName (key: any) {
    switch (key) {
      case 'N':
        return '保密'
      case 'F':
        return '女'
      case 'M':
        return '男'
    }
  }

  get areaList () {
    return (CommonModule as any).publicCache.region.result || []
  }

  private getAlias (field: any) {
    const labels = {}
    if (this.cusAllFields && this.cusAllFields.length) {
      this.cusAllFields.map(item => {
        labels[item.field] = item
      })
    }
    if (labels[field] && labels[field].alias) {
      return labels[field].alias
    } else if (labels[field] && labels[field].name) {
      return labels[field].name
    } else {
      return ''
    }
  }

  public async getRecord () {
    const { page, limit } = this.pageData
    const sendData = {
      page,
      limit,
      customerId: this.customerId,
      operateUser: this.searchForm.operateUser,
      operateType: this.searchForm.operateType
    }
    const params = {
      url: '/server-crm/action/customerLog/list',
      method: 'POST',
      data: sendData
    }
    const res = await commonAction(params)
    if (res.success && res.data) {
      res.data.list.map(item => {
        item.name = this.getAgentName(item.createUser)
        item.operateName = this.getOperateTypeName(item.operateType)
        if (['create_contactor', 'delete_contactor'].includes(item.operateType)) {
          item.isUpdate = 'nochange'
          item.value = []
          const valueObj = item.operateType === 'create_contactor' ? item.changes[0].newValue : item.changes[0].oldValue
          Object.keys(valueObj).map(key => {
            if (this.getLabel(key)) {
              if (key === 'phone') {
                item.value.push({
                  label: this.getLabel(key),
                  val: checkHideTel(valueObj[key])
                })
              } else {
                item.value.push({ label: this.getLabel(key), val: valueObj[key] })
              }
            }
          })
        } else if (['create_contactor_address', 'delete_contactor_address'].includes(item.operateType)) {
          item.isUpdate = 'nochange'
          item.value = []
          item.changes.map(it => {
            if (['address'].includes(it.fieldKey)) {
              const areaName = []
              this.getArea(item.operateType === 'create_contactor_address' ? it.newValue : it.oldValue, 0, this.areaList, areaName)
              item.value.push({ label: this.getLabel(it.fieldKey), val: areaName.join('') })
            } else {
              item.value.push({
                label: this.getLabel(it.fieldKey),
                val: item.operateType === 'create_contactor_address' ? it.newValue : it.oldValue
              })
            }
          })
        } else if (['update_contactor', 'update_contactor_address'].includes(item.operateType)) {
          item.isUpdate = 'change'
          if (item.changes && item.changes.length) {
            item.changes.map(it => {
              it.label = this.getLabel(it.fieldKey)
              if (['address'].includes(it.fieldKey)) {
                const newAreaName = []
                const oldAreaName = []
                this.getArea(it.newValue, 0, this.areaList, newAreaName)
                this.getArea(it.oldValue, 0, this.areaList, oldAreaName)
                it.newValue = newAreaName.join('')
                it.oldValue = oldAreaName.join('')
              } else if (['phone'].includes(it.fieldKey)) {
                it.newValue = checkHideTel(it.newValue)
                it.oldValue = checkHideTel(it.oldValue)
              }
            })
          }
        } else if (['manual_assign', 'create_customer_single_assign', 'incoming_auto_create', 'import_customer_no_assign', 'import_customer_assign', 'open_api_create_customer_assign'].includes(item.operateType)) {
          item.isUpdate = 'change'
          if (item.changes && item.changes.length) {
            item.changes.map(it => {
              it.label = this.getLabel(it.fieldKey)
            })
          }
        } else if (['update_customer', 'open_api_update_customer'].includes(item.operateType)) {
          item.isUpdate = 'change'
          if (item.changes && item.changes.length) {
            item.changes.map(it => {
              it.label = it.fieldKey
              console.log(this.getAlias('email'), this.getAlias('gender'), 888)
              if (it.fieldKey === '省市区' || it.fieldKey === this.getAlias('region')) { // 省市区
                // 级联菜单可多选
                // it.newValue = it.newValue && it.newValue.map(v => {
                //   const areaName = []
                //   this.getArea(v, 0, this.areaList, areaName)
                //   return areaName.join('')
                // })
                // it.oldValue = it.oldValue && it.oldValue.map(v => {
                //   const areaName = []
                //   this.getArea(v, 0, this.areaList, areaName)
                //   return areaName.join('')
                // })
                // 级联菜单单选
                if (it.newValue) {
                  const newAreaName = []
                  this.getArea(it.newValue, 0, this.areaList, newAreaName)
                  it.newValue = newAreaName.join('')
                }
                if (it.oldValue) {
                  const oldAreaName = []
                  this.getArea(it.oldValue, 0, this.areaList, oldAreaName)
                  it.oldValue = oldAreaName.join('')
                }
              } else if (['QQ', '微信号', '邮箱', this.getAlias('qq'), this.getAlias('wechat'), this.getAlias('email')].includes(it.fieldKey)) {
                it.newValue = it.newValue && it.newValue.map(mo => mo.value)
                it.oldValue = it.oldValue && it.oldValue.map(mo => mo.value)
              } else if (['手机号码', this.getAlias('mobile')].includes(it.fieldKey)) {
                it.newValue = it.newValue && it.newValue.map(mo => checkHideTel(mo.value))
                it.oldValue = it.oldValue && it.oldValue.map(mo => checkHideTel(mo.value))
              } else if (['性别', this.getAlias('gender')].includes(it.fieldKey)) {
                it.newValue = this.getSexName(it.newValue)
                it.oldValue = this.getSexName(it.oldValue)
              }
            })
          }
        } else if (['visitor_assign_customer', 'cancel_assign_visitor_customer'].includes(item.operateType)) {
          item.isUpdate = 'relation'
        }
      })
      this.recordData = this.recordData.concat(res.data.list)
      this.pageData.total = res.data.count
      if (this.pageData.total <= limit * page || res.data.list.length < 10) {
        this.allShow = true
      } else {
        this.allShow = false
      }
    }
  }

  public quickQuery () {
    this.pageData.page = 1
    this.recordData = []
    this.getRecord()
  }
}
</script>
<style lang="stylus" scoped>
.no-data
  background url('../../../assets/img/no-data.png') no-repeat center center
  width 100%
  height 200px
  background-size 267px auto
.OperateRecord
  width 100%
  height 100%
  .else
    text-align center
    color #999
    margin-top 50px
.line
  width 100%
  height 1px
  background #E7E9ED
</style>
